package com.ransj.iphone.utils;

import android.content.Context;
import android.content.IntentSender.SendIntentException;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import com.ransj.iphone.R;
import com.ransj.iphone.R.string;

/**
 * 
 * @author ranshengju
 * 
 */
public class ITracker {
	private static final String TAG = ITracker.class.getSimpleName();
	//category 
	public static final String CATEGORY_BUTTON = "button";
	//action
	public static final String ACTION_SHOW = "show";
	public static final String ACTION_CLICK = "click";
	private GoogleAnalyticsTracker mTracker;
	private boolean mIsTrackOk;
	private Context mContext;

	public ITracker(Context context) {
		mContext = context;
		init();
	}
	
	private void init(){
		try {
			mTracker = GoogleAnalyticsTracker.getInstance();
			mTracker.startNewSession(mContext.getString(R.string.tracker_key),
					mContext);
			mIsTrackOk = true;
		} catch (Exception e) {
			mIsTrackOk = false;
			ILog.getInstance().e(TAG, e);
		}
	}
	
	private void checkTracker(){
		if(!mIsTrackOk){
			init();
		}
	}
	
	public void trackPage(String page){
		try {
			checkTracker();
			if (mIsTrackOk) {
				mTracker.trackPageView(page);
				uploadData();
			}
		} catch (Exception e) {
			mIsTrackOk = false;
			ILog.getInstance().e(TAG, e);
		}
	}
	
	public void trackEvent(String category, String action, String label){
		try {
			checkTracker();
			if (mIsTrackOk) {
				mTracker.trackEvent(category , action, label, 0);
			}
		} catch (Exception e) {
			mIsTrackOk = false;
			ILog.getInstance().e(TAG, e);
		}
	}
	
	public void uploadData(){
		try {
			checkTracker();
			if (mIsTrackOk) {
				mTracker.dispatch();
			}
		} catch (Exception e) {
			mIsTrackOk = false;
			ILog.getInstance().e(TAG, e);
		}
	}
	
	public void stopTrack(){
		try {
			if(mIsTrackOk){
				uploadData();
				mTracker.stopSession();
				mTracker = null;
			}
		} catch (Exception e) {
			mIsTrackOk = false;
			ILog.getInstance().e(TAG, e);
		}
	}
}
